<template>
  <div class="work">
    <n-tabs type="segment" animated @update:value="updateTabs" class="work-tabs">
      <n-tab-pane name="chap1" tab="工作日程" class="tab-pane">
        <n-calendar v-model:value="calendar" #="{ year, month, date }" @update:value="handleUpdateValue">
          {{ year }}-{{ month }}-{{ date }}
          <br>
          <n-flex>
            <n-tag type="success" size="small" v-if="calendarTime(year, month, date, 1)">通过{{ calendarTime(year,
      month,
      date, 1)
              }}</n-tag>
            <n-tag type="error" size="small" v-if="calendarTime(year, month, date, 2)">不通过{{ calendarTime(year, month,
      date, 2)
              }}</n-tag>
            <n-tag type="warning" size="small" v-if="calendarTime(year, month, date, 0)">提交{{ calendarTime(year,
      month,
      date, 0)
              }}</n-tag>
          </n-flex>
        </n-calendar>

      </n-tab-pane>
      <n-tab-pane name="chap2" tab="工作报表" class="work-report tab-pane">
        <n-space class="work-report-space">
          <n-button type="primary" @click="$refs.fileInput.click()">提交工作报表</n-button>
        </n-space>
        <n-data-table :loading="tableLoading" :columns="columns" :data="data" :pagination="pagination"
          :single-line="false" />
      </n-tab-pane>
    </n-tabs>
    <input type="file" @change="fileChange" accept="*" style="display: none" ref="fileInput">

  </div>
</template>
<script setup>
import { getreport, uploadFile, addreport, delreport, updatereport, addcalendar, getcalendar } from "@/api"
import { h, computed } from "vue"
import { NButton, NTag, NPopconfirm } from 'naive-ui'
import moment from "moment";
import Store from "@/stores";
const store = Store();
const tableLoading = ref(false);
const base_url = process.env.baseURL
const calendarList = ref([]);
const data = ref([])
const form = ref([])
const calendar = ref(new Date().getTime());
const calendarTime = computed(() => {
  return function (year, month, date, status) {
    return calendarList.value.filter(item => item.status ===
      status && moment(item.time).format('YYYY-MM-DD') === moment(new Date((year + "-" + month + "-" +
        date))).format('YYYY-MM-DD')).length
  }
})
const pagination = {
  showSizePicker: true,
  pageSizes: [10, 30, 50, 100],//可切换的 每页条数
};
const columns = [
  {
    title: '报表编号',
    key: 'number'
  },
  {
    title: '提交时间',
    key: 'uploadTime'
  },
  {
    title: '审批时间',
    key: "approveTime",
  },
  {
    title: '报表下载',
    key: 'down',
    render(item) {
      return h(NButton,
        {
          type: "info",
          // quaternary: true,
          size: 'small',
          onClick: () => {
            window.open(base_url + item.url, "_blank");
          },
        },
        { default: () => "下载" }
      )
    }
  },
  {
    title: '审批',
    key: "approve",
    render(item) {
      const render = {
        0: h(NTag, { type: "warning", size: 'small', }, { default: () => "审批中" }),//审批中
        1: h(NTag, { type: "success", size: 'small', }, { default: () => "通过" }),//通过
        2: h(NTag, { type: "error", size: 'small', }, { default: () => "不通过" }),//不通过
      }
      const approve = [h(NPopconfirm,
        {
          onPositiveClick: () => {
            console.log(item);
            updatereport({ _id: item._id, status: 1, approveTime: moment().format('YYYY-MM-DD HH:mm:ss') }).then(res => {
              if (res.code != 200) return $message.error(res.message)
              $message.success(res.message)
              addcalendar({ userId: item.userId, status: 1, time: moment().format('YYYY-MM-DD HH:mm:ss') })
              getList()
            })
          },
        },
        {
          trigger: () => h(NButton,
            {
              type: "success",
              quaternary: true,
              size: 'small',
            },
            { default: () => "通过" }
          ), default: () => "审批通过"
        },
      ), h(NPopconfirm,
        {
          onPositiveClick: () => {
            console.log(item);
            updatereport({ _id: item._id, status: 2, approveTime: moment().format('YYYY-MM-DD HH:mm:ss') }).then(res => {
              if (res.code != 200) return $message.error(res.message)
              $message.success(res.message)
              addcalendar({ userId: item.userId, status: 2, time: moment().format('YYYY-MM-DD HH:mm:ss') })
              getList()
            })
          },
        },
        {
          trigger: () => h(NButton,
            {
              type: "error",
              quaternary: true,
              size: 'small',
            },
            { default: () => "驳回" }
          ), default: () => "审批驳回"
        },
      )]
      const button = store.userInfo.post == 4 && item.status == 0 ? approve : render[item.status]
      return button
    }
  },
  {
    title: '操作',
    key: "set",
    render(item) {
      return h(NPopconfirm,
        {
          onPositiveClick: () => {
            console.log(item);
            delreport({ _id: item._id }).then(res => {
              if (res.code != 200) return $message.error(res.message)
              $message.success(res.message)
              getList()
            })
          },
        },
        {
          trigger: () => h(NButton,
            {
              type: "error",
              quaternary: true,
              disabled: item.userId != store.userInfo._id,
              size: 'small',
            },
            { default: () => "删除" }
          ), default: () => "确认删除"
        },
      )
    }
  },
]
function handleUpdateValue(date) {
  // console.log(date);
  console.log(moment(date).format("YYYY-MM-DD"));
}
function fileChange(e) {
  const file = e.target.files[0]
  const formdata = new FormData()
  e.target.value = ''
  formdata.append('file', file)
  console.log(file);
  const messageLoading = $message.loading("报表上传中...", { duration: 0, })
  uploadFile(formdata).then(res => {
    if (res.code != 200) return $message.error(res.message)
    // $message.success(res.message)
    const data = {
      userId: store.userInfo._id,
      number: res.url.split("/").at(-1).split(".")[0],
      url: res.url,
      uploadTime: moment().format("YYYY-MM-DD HH:mm:ss"),
      status: 0,//0待审批，1已通过,2已驳回
    }
    addreport(data).then(res => {
      messageLoading.destroy()
      if (res.code != 200) return $message.error(res.message)
      $message.success(res.message)
      addcalendar({ userId: store.userInfo._id, status: 0, time: moment().format('YYYY-MM-DD HH:mm:ss') })
      getList()
    })
  })

};
getList()
function getList() {
  tableLoading.value = true
  getreport(store.userInfo.post == 4 ? {} : { userId: store.userInfo._id }).then(res => {
    tableLoading.value = false
    if (res.code != 200) return $message.error(res.message)
    data.value = [...res.data.filter(item => item.status == 0), ...res.data.filter(item => item.status != 0)]
  })
}
getcalendarList()
function getcalendarList() {
  getcalendar({ userId: store.userInfo._id }).then(res => {
    if (res.code != 200) return $message.error(res.message)
    calendarList.value = res.data
  })
}
function updateTabs(params) {
  // console.log(params);
  if (params == "chap1") {
    getcalendarList()
  } else {
    getList()
  }
}
</script>

<style lang="less" scoped>
.work-report {
  .work-report-space {
    margin-bottom: 15px;
  }
}


.work-tabs {

  // border: 1px solid black;
  height: 100%;
  // overflow: auto;
}

.work {
  height: 100%;
  overflow: auto;
}
</style>